package org.jiucheng.magpiebridge.client.aio;

import java.nio.ByteBuffer;
import java.nio.channels.CompletionHandler;

import org.jiucheng.magpiebridge.client.util.ClientCfg;
import org.jiucheng.magpiebridge.protocol.Message;

/**
 * 
 * @author jiucheng
 *
 */
public class ClientEstablishmentCompletionHandler implements CompletionHandler<Void, ClientAttachment> {

	public void completed(Void result, ClientAttachment attachment) {
		Message message = new Message();
        message.setMagic(Message.MAGIC);
        message.setType(Message.Type.AUTH);
        byte[] data = ClientCfg.getClientKey().getBytes();
        message.setData(data);
        message.setSize(data.length);
        ByteBuffer buffer = Message.toByteBuffer(message);
        if (attachment.canWrited()) {
            attachment.getClient().write(buffer, attachment.setWriteByteBuffer(buffer), attachment.getClientWriteCompletionHandler());
        }
	}

	public void failed(Throwable exc, ClientAttachment attachment) {
		System.out.println("establish error");
		attachment.setFailed(true);
	}
}
